package org.github.project.zk.useage;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 原生客户端操作
 *
 * @auther yang
 * @date 2022/1/22 16:24
 */
public class ZooKeeperOperationDemo {

    public static void main(String[] args) throws Exception {
        ZooKeeper zk = new ZooKeeper("123.57.9.58:2181", 5000, System.out::println);
        System.out.println("OK");
//        String createdResult = create(zk, "/hello", "Hello World");
//        System.out.println("createdResult: " + createdResult);
//        System.out.println("getData: " + getData(zk, "/hello"));
//        System.out.println(setData(zk, "/hello", "fine"));
        delete(zk, "/hello");
    }


    // 创建结点
    public static String create(ZooKeeper zk, String path, String data) throws Exception {
        return zk.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    // 获得结点数据
    public static String getData(ZooKeeper zk, String path) throws Exception {
        Stat stat = new Stat();
        String data = new String(zk.getData(path, false, stat), StandardCharsets.UTF_8);
        System.out.println("结点状态: " + stat.toString());
        System.out.println("cversion:" + stat.getVersion());
        return data;
    }

    // 修改结点数据
    public static Stat setData(ZooKeeper zk, String path, String newData) throws Exception {
        Stat stat = new Stat();
        zk.getData(path, false, stat);
        return zk.setData(path, newData.getBytes(), stat.getVersion());
    }

    // 删除结点
    public static void delete(ZooKeeper zk, String path) throws Exception {
        Stat stat = new Stat();
        zk.getData(path, false, stat);
        zk.delete(path, stat.getVersion());
    }
}
